package org.laizili.solution.leetcode;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * <a href="https://leetcode.cn/problems/k-diff-pairs-in-an-array/">532. 数组中的 k-diff 数对</a>
 */
public class Problem532 {
    private static class Solution {
        record Pair(int i, int j) {
            @Override
            public boolean equals(Object o) {
                if (this == o) return true;
                if (o == null || getClass() != o.getClass()) return false;
                Pair pair = (Pair) o;
                return i == pair.i && j == pair.j;
            }

            @Override
            public int hashCode() {
                return Objects.hash(i, j);
            }
        }

        public int findPairs(int[] nums, int k) {
            Arrays.sort(nums);
            Set<Pair> pairSet = new HashSet<>();
            int left = 0, right = 1;
            int len = nums.length;
            while (right < len) {
                if (left == right) {
                    right++;
                    if (right >= len) {
                        break;
                    }
                }
                int diff = nums[right] - nums[left];
                if (diff == k) {
                    pairSet.add(new Pair(nums[left], nums[right]));
                    right++;
                } else if (diff < k) {
                    right++;
                } else {
                    left++;
                }
            }
            return pairSet.size();
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution().findPairs(new int[]{1, 2, 6}, 4));
    }
}
